﻿//using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler.Encoder;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace aier.wx.api.selfhost
{
    public class CustomJwtFormat : ISecureDataFormat<AuthenticationTicket>
    {
        private readonly byte[] _secret;
        private readonly string _issuer;

        public CustomJwtFormat(string issuer, byte[] secret)
        {
            _issuer = issuer;
            _secret = secret;
        }

        /// <summary>
        /// 生成令牌
        /// </summary>
        /// <param name="data">票据</param>
        /// <returns></returns>
        public string Protect(AuthenticationTicket data)
        {
            var secretStr = ConfigurationManager.AppSettings["SecretKey"];
            //"IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw"
            var secret = TextEncodings.Base64Url.Decode(secretStr);//秘钥
            var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(secret);
            //var signingKey = new InMemorySymmetricSecurityKey(_secret);
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey,
               SecurityAlgorithms.HmacSha256Signature);
            var issued = data.Properties.IssuedUtc;
            var expires = data.Properties.ExpiresUtc;

            return new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(_issuer, "Any", data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingCredentials));
        }

        /// <summary>
        /// 从token中解码，返回一个票据信息
        /// </summary>
        /// <param name="protectedText">受保护的文本，也就是token</param>
        /// <returns></returns>
        public AuthenticationTicket Unprotect(string protectedText)
        {
            var jst = new JwtSecurityTokenHandler();
            var token = (JwtSecurityToken)jst.ReadToken(protectedText);

            var identity = new ClaimsIdentity(token.Claims);
            var ticket = new AuthenticationTicket(identity, new AuthenticationProperties() { });
            return ticket;
        }
    }
}
